﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ProblemaShowroom
{
    /// <summary>
    /// Also acts like an Object Pool.
    /// If client realeases car objects, the showroom reuses them.
    /// </summary>
    class Showroom
    {
        private CarManufacturer _manufacturer;

        private List<Car> _cars;

        public Showroom(CarManufacturer manufacturer)
        {
            _manufacturer = manufacturer;
            _cars = new List<Car>();
        }

        public void SellCar(Client client)
        {
            CarType type;

            GetCarType(out type);

            Car car = (from c in _cars
                       where c.GetType().Name.Contains(type.ToString())
                       select c).FirstOrDefault();

            if (car == null) // empty pool => create car
            {
                car = _manufacturer.GetCar(type);
            }
            else // found car => just initialize
            {
                InitCar(car);
            }
            
            client.AddCar(car);
        }

        private void InitCar(Car car)
        {
            string color, transmission;

            Console.Write("Color? ");
            color = Console.ReadLine();

            Console.Write("Transmission(Automatic/Manual)? ");
            transmission = Console.ReadLine();

            car.Init(color, transmission);
        }

        public void CollectCar(Car car)
        {
            _cars.Add(car);
        }

        private void GetCarType(out CarType type)
        {
            Console.WriteLine("Choose Car Type:");
            object defaultType;
            foreach (var e in Enum.GetValues(typeof(CarType)))
            {
                Console.WriteLine("\t{0}. {1}", (int)e, Enum.GetName(typeof(CarType), e));
                defaultType = e;
            }

            Console.Write("? ");
            type = (CarType)Enum.Parse(typeof(CarType), Enum.GetName(typeof(CarType), int.Parse(Console.ReadLine())));
        }
    }
}
